package com.tutk.AV_Player;

import android.media.AudioFormat;
import android.media.AudioTrack;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.os.Environment;
import android.util.Log;

import com.tutk.util.MyApplication;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;

import static android.media.AudioFormat.ENCODING_PCM_16BIT;

/**
 * 音频解码显示
 */
public class AudioPlayer extends Thread{
    private MediaCodec decoder;
    private String mime = "audio/aac";

        @Override
    public void run() {

            //初始化解码器
            try {

                sleep(500);
                MediaFormat format = new MediaFormat();
                format.setString(MediaFormat.KEY_MIME, mime);//mime类型设置
                format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 2);//双声道
                format.setInteger(MediaFormat.KEY_BIT_RATE, 96000);//比特率
                format.setInteger(MediaFormat.KEY_SAMPLE_RATE, 44100);//采样率

                decoder = MediaCodec.createDecoderByType(mime);//解码器类型为音频AAC
                decoder.configure(format, null, null, 0);

                if (decoder == null) {
                    Log.e("system", "Create Audio MediaDecode Failed");
                    return;
                }

                decoder.start();

            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //开始解码
            ByteBuffer[] inputBuffers = decoder.getInputBuffers();
            ByteBuffer[] outputBuffers = decoder.getOutputBuffers();
            MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
            while (!Thread.interrupted()) {
                byte[] buf = MyApplication.getAudioBuffer();
                int inputIndex = decoder.dequeueInputBuffer(1000);

                if (inputIndex >= 0) {
                    ByteBuffer inputBuffer = inputBuffers[inputIndex];
                    inputBuffer.clear();
                    inputBuffer.put(buf);

                    decoder.queueInputBuffer(inputIndex, 0, buf.length, 0, 0);
                }
                int outIndex = decoder.dequeueOutputBuffer(info, 10000);
                while (outIndex >= 0) {
//                    ByteBuffer outputBuffer = outputBuffers[outIndex];
//                    outputBuffer.position(0);
//                    byte[] outData = new byte[info.size];
//                    outputBuffer.get(outData);

                    decoder.releaseOutputBuffer(outIndex, true);
                    outIndex = decoder.dequeueOutputBuffer(info, 0);
                }
            }
        }
}
